import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import readingTime from 'reading-time';

/**
 * 文档元数据接口
 * 定义文档的基本信息结构
 */
export interface DocMeta {
  title: string;
  description: string;
  category: string;
  order?: number;
  tags?: string[];
  author?: string;
  publishedAt?: string;
  updatedAt?: string;
  featured?: boolean;
  difficulty?: 'beginner' | 'intermediate' | 'advanced';
}

/**
 * 文档接口
 * 包含文档内容和元数据
 */
export interface Doc {
  slug: string;
  meta: DocMeta;
  content: string;
  readingTime: {
    text: string;
    minutes: number;
    time: number;
    words: number;
  };
  toc: TableOfContent[];
}

/**
 * 目录接口
 * 用于生成文档目录
 */
export interface TableOfContent {
  id: string;
  title: string;
  level: number;
  children?: TableOfContent[];
}

/**
 * 文档分类接口
 * 用于组织文档结构
 */
export interface DocCategory {
  name: string;
  slug: string;
  description: string;
  docs: Doc[];
  order: number;
}

const DOCS_PATH = path.join(process.cwd(), 'content/docs');

/**
 * 获取所有文档文件路径
 * 递归遍历文档目录
 */
function getDocFiles(dir: string = DOCS_PATH): string[] {
  if (!fs.existsSync(dir)) {
    return [];
  }

  const files: string[] = [];
  const items = fs.readdirSync(dir);

  for (const item of items) {
    const fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);

    if (stat.isDirectory()) {
      files.push(...getDocFiles(fullPath));
    } else if (item.endsWith('.mdx')) {
      files.push(fullPath);
    }
  }

  return files;
}

/**
 * 从文档内容生成目录
 * 解析标题生成导航目录
 */
function generateTableOfContents(content: string): TableOfContent[] {
  const headingRegex = /^(#{1,6})\s+(.+)$/gm;
  const headings: TableOfContent[] = [];
  let match;

  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length;
    const title = match[2].trim();
    const id = title
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-|-$/g, '');

    headings.push({
      id,
      title,
      level,
    });
  }

  return headings;
}

/**
 * 解析单个文档文件
 * 提取元数据和内容
 */
export function parseDoc(filePath: string): Doc {
  const fileContent = fs.readFileSync(filePath, 'utf8');
  const { data, content } = matter(fileContent);

  // 生成slug
  const relativePath = path.relative(DOCS_PATH, filePath);
  const slug = relativePath.replace(/\.mdx$/, '').replace(/\/index$/, '');

  // 计算阅读时间
  const readingTimeStats = readingTime(content);

  // 生成目录
  const toc = generateTableOfContents(content);

  return {
    slug,
    meta: data as DocMeta,
    content,
    readingTime: readingTimeStats,
    toc,
  };
}

/**
 * 获取所有文档
 * 返回解析后的文档列表
 */
export function getAllDocs(): Doc[] {
  const files = getDocFiles();
  const docs = files.map(parseDoc);

  // 按分类和顺序排序
  return docs.sort((a, b) => {
    if (a.meta.category !== b.meta.category) {
      return a.meta.category.localeCompare(b.meta.category);
    }
    return (a.meta.order || 999) - (b.meta.order || 999);
  });
}

/**
 * 根据slug获取文档
 * 查找特定文档
 */
export function getDocBySlug(slug: string): Doc | null {
  const docs = getAllDocs();
  return docs.find(doc => doc.slug === slug) || null;
}

/**
 * 按分类获取文档
 * 返回分类组织的文档结构
 */
export function getDocsByCategory(): DocCategory[] {
  const docs = getAllDocs();
  const categories = new Map<string, DocCategory>();

  docs.forEach(doc => {
    const categoryName = doc.meta.category;

    if (!categories.has(categoryName)) {
      categories.set(categoryName, {
        name: categoryName,
        slug: categoryName.toLowerCase().replace(/\s+/g, '-'),
        description: `${categoryName} 相关文档`,
        docs: [],
        order: getCategoryOrder(categoryName),
      });
    }

    categories.get(categoryName)!.docs.push(doc);
  });

  return Array.from(categories.values()).sort((a, b) => a.order - b.order);
}

/**
 * 获取分类排序
 * 定义文档分类的显示顺序
 */
function getCategoryOrder(category: string): number {
  const order: Record<string, number> = {
    快速开始: 1,
    核心概念: 2,
    API参考: 3,
    金融场景: 4,
    最佳实践: 5,
    故障排除: 6,
  };

  return order[category] || 999;
}

/**
 * 搜索文档
 * 根据关键词搜索文档内容
 */
export function searchDocs(query: string): Doc[] {
  const docs = getAllDocs();
  const lowercaseQuery = query.toLowerCase();

  return docs.filter(doc => {
    const searchText = [
      doc.meta.title,
      doc.meta.description,
      doc.content,
      ...(doc.meta.tags || []),
    ]
      .join(' ')
      .toLowerCase();

    return searchText.includes(lowercaseQuery);
  });
}

/**
 * 获取相关文档
 * 基于标签和分类推荐相关文档
 */
export function getRelatedDocs(doc: Doc, limit: number = 3): Doc[] {
  const allDocs = getAllDocs().filter(d => d.slug !== doc.slug);

  // 计算相关性分数
  const scored = allDocs.map(otherDoc => {
    let score = 0;

    // 同分类加分
    if (otherDoc.meta.category === doc.meta.category) {
      score += 3;
    }

    // 共同标签加分
    const commonTags = (doc.meta.tags || []).filter(tag =>
      (otherDoc.meta.tags || []).includes(tag)
    );
    score += commonTags.length * 2;

    return { doc: otherDoc, score };
  });

  return scored
    .sort((a, b) => b.score - a.score)
    .slice(0, limit)
    .map(item => item.doc);
}
